package com.cloud.easy.im.netty.handler;

import com.cloud.easy.im.argeement.Agreement;
import com.cloud.easy.im.argeement.AgreementFactory;
import com.cloud.easy.im.handler.AbstractServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义用于接受netty正常读写逻辑handler
 *
 * @author wangjian
 * @version 0.1.0
 * @create 2020年09月03日10:16 上午
 */
public class UDPClientInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private static final Logger logger = LoggerFactory.getLogger(UDPClientInboundHandler.class);

    private AbstractServerHandler abstractServerHandler;

    public UDPClientInboundHandler(AbstractServerHandler abstractServerHandler) {
        this.abstractServerHandler = abstractServerHandler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        Agreement dataFromClient = AgreementFactory.parseAgreement(msg);
        abstractServerHandler.messageReceived(ctx.channel(), dataFromClient);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        abstractServerHandler.sessionCreat(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        abstractServerHandler.sessionClosed(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            abstractServerHandler.exceptionCaught(ctx.channel(), cause);
        } catch (Exception ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}
